<?php

namespace app\adminapi\controller;

use think\Controller;
use app\common\model\Admin as AdminModel;
class Login extends BaseApi
{
    public function captcha(){
        //验证码标识
        $uniqud = uniqid(mt_rand(100000,999999));
        $data = [
            'src' => captcha_src($uniqud),
           'uniqid' => $uniqud,
        ];
        $this-> ok($data);
    }
    public function login(){
      
        $param = input();
        $password=encrypt_password($param['password']);
      
        $validate = $this->validate($param,[
            'username|用户名' => 'require',
            'password|密码' => 'require',   
            'code|验证码' =>'require',
            'uniqid|验证码标识' =>'require',

        ]);
        
        if($validate!==true){
            $this->fail($validate);
        }
       
      
        session_id(cache('session_id_'.$param['uniqid']));
        if(!captcha_check($param['code'],$param['uniqid'])){
            $this->fail('验证码错误');
        }
        $where = [
            'username' => $param['username'],
            'password' => encrypt_password($param['password'])
        ];
        $info = AdminModel::where($where)->find();
        if(!$info){
            //用户名或者密码错误
            $this->fail('用户名或者密码错误');
        }
        $data = [
            'token'=>tools\jwt\Token::getToken([
                'id'=>$info['id'],
            
            ]),
            $data['user_id']=$info['id'],
            $data['user_id'] = $info->id;
            $data['username'] = $info->username;
            $data['nickname'] = $info->nickname;
            $data['email'] = $info->email;
        ]
        $this->ok($info);
    }
}
